package com.github.weixin.demo.controller;

import java.awt.color.CMMException;
import java.util.Comparator;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.weixin.demo.util.MD5Util;
import com.github.weixin.demo.util.Sha1Util;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpDeviceService;
import me.chanjar.weixin.mp.api.WxMpService;

@Controller
public class ViewController{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired WxMpService service;
	WxMpDeviceService ds;
	@PostConstruct
	private void init(){
		ds = service.getDeviceService();
	}
	@RequestMapping(value="/views/{vn}")
	public String views(@PathVariable("vn")String vn,HttpServletRequest req,HttpServletResponse res) throws Exception{
		if(vn.contains("userindex")){
			String jsticket = service.getJsapiTicket();
			String nonceStr = Sha1Util.getNonceStr();
			String timestamp = Sha1Util.getTimeStamp();
			
			//req.setAttribute("timestamp", timestamp);
			req.setAttribute("timestamp", timestamp);
			req.setAttribute("nonceStr", nonceStr);
			req.setAttribute("signature", timestamp);
			SM sm = new SM();
			sm.put("jsapi_ticket",jsticket);
			sm.put("noncestr",nonceStr);
			sm.put("timestamp", timestamp);
			String url = req.getScheme()+"://"+req.getServerName()+req.getRequestURI();
			sm.put("url",url);
			
			req.setAttribute("url", sm.get("url"));
			req.setAttribute("noncestr", sm.get("noncestr"));
			String sig = Sha1Util.createSHA1Sign(sm);
			req.setAttribute("signature", sig);
		}
		
		return vn;
		
	}
	
}
class SM extends TreeMap<String,String>{
	public SM() {
		super(new Comparator<String>(){

			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				return o1.compareTo(o2);
			}
			
		});
	}
}
